package com.guit.hrms.interceptors;

import com.guit.hrms.service.TokenService;
import com.guit.hrms.utils.JwtUtil;
import com.guit.hrms.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override //请求到达接口之前执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getRequestURI();
        System.out.println("请求路径: " + path);  // 直接用 System.out 打印，确保能看到

        // 如果是/articles/路径，检查是否以数字结尾
        if (path.startsWith("/api/articles/") && (path.matches("/api/articles/[0-9]+") || path.matches("/api/articles/type/*"))) {
            return true;
        }

        System.out.println("header； "+ request.getHeader("Token"));
        System.out.println(request.getMethod());
        String token;
        // 获取Header中的token
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        } else {
            token = request.getHeader("Token");
            System.out.println("Token: " + token);
        }
        if (token != null) {
            try {
                Map<String,Object> claims = JwtUtil.parseToken(token);
                System.out.println("解析结果: " + claims);

                String employeeId = claims.get("employeeId").toString();

                // 验证是否为当前有效token
                if (!tokenService.validateToken(employeeId, token)) {
                    // token不是最新的，返回401错误
                    response.setStatus(401);
                    response.setContentType("application/json;charset=utf-8");
                    PrintWriter writer = response.getWriter();
                    writer.write("{\"code\":401,\"message\":\"您的账号已在其他设备登录，请重新登录\"}");
                    writer.flush();
                    writer.close();
                    return false;
                }

                ThreadLocalUtil.set(claims);
                return true;
            } catch (Exception e) {
                e.printStackTrace();  // 打印完整的错误堆栈
                response.setStatus(401);
                return false;
            }
        }
        response.setStatus(401);
        return false;
    }

    @Override //请求（接口）结束后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
